<!DOCTYPE html>
<html lang="zh-CN">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>收支统计</title>
    <script src="./js/echarts.min.js"></script>
    <style>
        .chart-container {
            width: 100%;
            height: 400px;
            margin: 20px 0;
        }
        .chart-wrapper {
            padding: 20px;
            max-width: 1200px;
            margin: 0 auto;
        }
        h2 {
            text-align: center;
            color: #333;
        }
        .summary {
            margin: 20px 0;
            padding: 15px;
            background-color: #f8f9fa;
            border-radius: 5px;
            display: flex;
            justify-content: space-around;
        }
        .summary p {
            margin: 0;
            padding: 10px;
            font-size: 16px;
        }
        .income {
            color: #ee6666;  /* 红色 */
        }
        .expense {
            color: #91cc75;  /* 绿色 */
        }
        .balance {
            transition: color 0.3s;
        }
        .balance.positive {
            color: #ee6666;  /* 正数显示红色 */
        }
        .balance.negative {
            color: #91cc75;  /* 负数显示绿色 */
        }
        .type-filter {
            text-align: center;
            margin-bottom: 15px;
        }
        .type-filter select {
            padding: 5px 10px;
            border-radius: 4px;
            border: 1px solid #ddd;
        }
    </style>
</head>
<body>
    <div class="chart-wrapper">
        <div class="year-selector">
            <label for="year">选择年份：</label>
            <select id="year">
                <option value="2024">2024年</option>
                <option value="2023">2023年</option>
            </select>
        </div>
        
        <h2>年度汇总</h2>
        <div class="summary">
            <p>年度总收入：<span id="yearTotalIncome" class="income">0</span> 元</p>
            <p>年度总支出：<span id="yearTotalExpense" class="expense">0</span> 元</p>
            <p>年度结余：<span id="yearBalance" class="balance">0</span> 元</p>
        </div>

        <h2>月度收支统计</h2>
        <div id="monthlyChart" class="chart-container"></div>
        
        <h2>收支类型分布</h2>
        <div class="type-filter">
            <label for="typeFilter">显示类型：</label>
            <select id="typeFilter">
                <option value="all">全部</option>
                <option value="income">仅收入</option>
                <option value="expense">仅支出</option>
            </select>
        </div>
        <div id="typeChart" class="chart-container"></div>
    </div>

    <script>
        // 初始化图表
        const monthlyChart = echarts.init(document.getElementById('monthlyChart'));
        const typeChart = echarts.init(document.getElementById('typeChart'));

        // 月度收支统计图表配置
        const monthlyOption = {
            tooltip: {
                trigger: 'axis',
                axisPointer: {
                    type: 'shadow'
                }
            },
            legend: {
                data: ['收入', '支出']
            },
            xAxis: {
                type: 'category',
                data: ['1月', '2月', '3月', '4月', '5月', '6月']
            },
            yAxis: {
                type: 'value',
                name: '金额（元）'
            },
            series: [
                {
                    name: '收入',
                    type: 'bar',
                    data: [0, 0, 0, 0, 0, 0],
                    itemStyle: {
                        color: '#ee6666'
                    }
                },
                {
                    name: '支出',
                    type: 'bar',
                    data: [0, 0, 0, 0, 0, 0],
                    itemStyle: {
                        color: '#91cc75'
                    }
                }
            ]
        };

        // 添加图表点击事件
        monthlyChart.on('click', function(params) {
            const month = (params.dataIndex + 1).toString().padStart(2, '0'); // 获取月份并补零
            const year = yearSelect.value;
            // 跳转到月度详情页面
            window.location.href = `monthly_detail.html?year=${year}&month=${month}`;
        });

        // 收支类型分布图表配置
        const typeOption = {
            tooltip: {
                trigger: 'item'
            },
            legend: {
                orient: 'vertical',
                left: 'left'
            },
            series: [
                {
                    name: '收支类型',
                    type: 'pie',
                    radius: '50%',
                    data: [],
                    emphasis: {
                        itemStyle: {
                            shadowBlur: 10,
                            shadowOffsetX: 0,
                            shadowColor: 'rgba(0, 0, 0, 0.5)'
                        }
                    }
                }
            ]
        };

        // 渲染图表
        monthlyChart.setOption(monthlyOption);
        typeChart.setOption(typeOption);

        // 响应式处理
        window.addEventListener('resize', function() {
            monthlyChart.resize();
            typeChart.resize();
        });

    

        // 获取当前年份并生成最近5年的选项
        const currentYear = new Date().getFullYear();
        const yearSelect = document.getElementById('year');
        
        // 清空现有选项
        yearSelect.innerHTML = '';
        
        // 添加最近5年的选项
        for(let i = 0; i < 5; i++) {
            const year = currentYear - i;
            const option = document.createElement('option');
            option.value = year;
            option.textContent = year + '年';
            yearSelect.appendChild(option);
        }
        
        // 设置默认选中当前年份
        yearSelect.value = currentYear.toString();

        // 加载统计数据
        function loadStatistics(year) {
            fetch(`/api/statistics?year=${year}`)
                .then(response => response.json())
                .then(result => {
                    if (result.success) {
                        const data = result.data;
                        
                        // 计算年度汇总数据
                        const yearTotalIncome = data.monthlyStats.monthlyIncome.reduce((sum, val) => sum + val, 0);
                        const yearTotalExpense = data.monthlyStats.monthlyExpense.reduce((sum, val) => sum + val, 0);
                        const yearBalance = yearTotalIncome - yearTotalExpense;
                        
                        // 更新年度汇总显示
                        document.getElementById('yearTotalIncome').textContent = yearTotalIncome.toFixed(2);
                        document.getElementById('yearTotalExpense').textContent = yearTotalExpense.toFixed(2);
                        
                        // 更新结余并设置颜色
                        const balanceElement = document.getElementById('yearBalance');
                        balanceElement.textContent = yearBalance.toFixed(2);
                        balanceElement.className = 'balance ' + (yearBalance >= 0 ? 'positive' : 'negative');
                        
                        // 更新月度统计图表
                        monthlyChart.setOption({
                            xAxis: {
                                data: ['1月', '2月', '3月', '4月', '5月', '6月', '7月', '8月', '9月', '10月', '11月', '12月']
                            },
                            series: [
                                {
                                    name: '收入',
                                    data: data.monthlyStats.monthlyIncome
                                },
                                {
                                    name: '支出',
                                    data: data.monthlyStats.monthlyExpense
                                }
                            ]
                        });
                        
                        // 保存完整数据 - 直接使用后端返回的数据
                        window.fullTypeData = data.typeDistribution;
                        
                        // 更新类型分布图表
                        updateTypeChart('all');
                    } else {
                        alert('获取统计数据失败：' + result.message);
                    }
                })
                .catch(error => {
                    console.error('获取统计数据出错：', error);
                    alert('获取统计数据出错，请查看控制台了解详情');
                });
        }

        // 根据筛选条件更新类型分布图表
        function updateTypeChart(filterType) {
            if (!window.fullTypeData) return;
            
            let filteredData;
            if (filterType === 'all') {
                filteredData = window.fullTypeData;
            } else {
                filteredData = window.fullTypeData.filter(item => item.type === filterType);
            }
            
            typeChart.setOption({
                series: [
                    {
                        data: filteredData.map(item => ({
                            value: item.value,
                            name: item.name,
                            itemStyle: {
                                color: item.color // 使用后端提供的颜色
                            }
                        }))
                    }
                ]
            });
        }

        // 监听年份选择变化
        yearSelect.addEventListener('change', function() {
            loadStatistics(this.value);
        });
        
        // 监听类型筛选变化
        document.getElementById('typeFilter').addEventListener('change', function() {
            updateTypeChart(this.value);
        });

        // 初始加载数据
        loadStatistics(currentYear);
    </script>
</body>
</html>